# -*- coding: utf-8 -*-
from querier.esquerier import ElasticSearchQuerier
import querier.weibo.utils as utils


class WeiboPostAllQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type):
        super(WeiboPostAllQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type

    def _build_query(self, args):
        user_id = args.get('user_id', None)
        filters = args.get('filters', {})
        filter_clause = [{"term": {"user_id": user_id}}]
        if filters:
            filter_clause += add_filter_range_clause(filters, 'publish_timestamp')

        if user_id is None:
            raise ValueError('"user_id" is needed.')
        from_ = args.get('from', 0)
        size_ = args.get('size', 10)

        query = {"query": {
            "bool": {
                "filter": filter_clause
            }
        }, 'from': from_, 'size': size_, 'sort': [{'publish_timestamp': 'desc'}]}
        return query, {}, {}

    def _build_result(self, es_result, param):
        total = es_result['hits']['total']
        posts = []
        for hit in es_result['hits']['hits']:
            posts.append(extractResult(hit))
        return {
            'total': total,
            'keywords': [],
            'posts': posts
        }


def add_filter_range_clause(filters, key):
    if key in filters:
        if filters[key]:
            clause = []
            fk = filters[key]
            if not isinstance(fk, list) or len(fk) < 1:
                pass
            else:
                min_fk = fk[0]
                if len(fk) >= 2:
                    max_fk = fk[1]
                else:
                    max_fk = None
                if min_fk is not None and min_fk != 'null':
                    clause.append({'range': {key: {"gte": min_fk}}})
                if max_fk is not None and max_fk != 'null':
                    clause.append({'range': {key: {"lte": max_fk}}})
    return clause


def extractResult(hit):
    source_ = hit['_source']

    return utils.extract_post_from_source(source_)
